import 'package:amap_search_fluttify/amap_search_fluttify.dart';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/singleton/amap_repository/amap_repository.dart';
import 'package:e_reception_flutter/singleton/location_repository/location_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/company/choose_city/bean/choose_city_list_item_bean.dart';
import 'package:e_reception_flutter/ui/company/choose_city/choose_city_page.dart';
import 'package:e_reception_flutter/ui/company/company_detail/company_address/punch_rule_location_page.dart';
import 'package:e_reception_flutter/ui/company/company_register/bean/company_register_upload_bean.dart';
import 'package:e_reception_flutter/utils/address_about_utils.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_location_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_widget_lib.dart';

import 'new_terminal_list_view_model.dart';

class AddChannelOrgPage extends StatefulWidget {

  final VoidCallback voidCallback;
  final String defaultGps;
  const AddChannelOrgPage({Key key, this.voidCallback, this.defaultGps}) : super(key: key);

  static const String ROUTER = "AddChannelOrgPage";

  @override
  _AddChannelOrgPageState createState() => _AddChannelOrgPageState();

  static Future<bool> navigatorPush(BuildContext context, String defaultGps,VoidCallback voidCallback) {
    return RouterUtils.routeForFutureResult(
      context,
      AddChannelOrgPage(
          defaultGps:defaultGps,
          voidCallback:voidCallback
      ),
      routeName: AddChannelOrgPage.ROUTER,
    );
  }
}

class _AddChannelOrgPageState extends BaseState<AddChannelOrgPage> {

  TextEditingController _locationEditingController;
  TextEditingController _locationAddressController;
  CompanyRegisterUploadBean _uploadBean;
  Map<String, ChooseCityListItemBean> _resultLocationMap;

  TextEditingController _editingAddressController;

  VgLocation _locationPlugin;


  String province;
  String city ;
  String dirstrict;

  bool buttonFull = false;

  String gps;

  String addrCode;

  String gpsadress;

  var  lastPopTime;

  NewTerminalListViewModel _viewModel;
  TextEditingController _nameController;
  bool isAlive = false;


  _initLocation(){
    _locationPlugin = VgLocation();
    _locationPlugin.requestSingleLocation((locationMap) {
      print("能不能收到");
      var transResult = VgLocationUtils.transLocationToMap(locationMap);
      if (transResult == null) {
        return;
      }
      _resultLocationMap = transResult;
      _setLocationEditingValue();
      _setAddressGps();
      _notifyChange();
    });
  }

  LatLng latLong(){
    LatLng latLng; // 处理gps
    if(StringUtils.isNotEmpty(widget?.defaultGps) && StringUtils.isEmpty(gps)){
      if(widget?.defaultGps?.contains(",")){
        latLng = latLogDegree(widget?.defaultGps);
      }
    }else if(StringUtils.isNotEmpty(gps)){
      if(gps?.contains(",")){
        String newGps = gps?.replaceAll("°E", "")?.replaceAll("°N", "");
        latLng = latLogDegree(newGps);
      }
      setState(() { });
    }
    return latLng;
  }

  LatLng latLogDegree(String gps){
    return LatLng(double.parse(gps?.split(",")[0]),double.parse(gps.split(",")[1]));
  }

  @override
  void dispose() {
    _locationEditingController?.dispose();
    _editingAddressController?.dispose();
    if (_locationPlugin != null) _locationPlugin.dispose();
    super.dispose();
  }


  ///通知更新
  _notifyChange() {
    if (_uploadBean == null) {
      _uploadBean = CompanyRegisterUploadBean();
    }

    _uploadBean.setValue(
        locaiton: _locationEditingController?.text?.trim(),
        locationMap: _resultLocationMap,
        address: _editingAddressController?.text?.trim(),
        gps:_locationAddressController?.text
    );
    _showBoutton();
  }

  void _setAddressGps(){
    if(StringUtils.isEmpty(_editingAddressController?.text)){
      // _editingAddressController?.text = widget?.itemBean?.address;
    }
  }

  void _setLocationEditingValue() {
    if(StringUtils.isNotEmpty(widget?.defaultGps) && StringUtils.isEmpty(gps)){
      gps = AddressAboutUtils.getLongitudeAndLatitude(widget?.defaultGps?.split(",")[1], widget?.defaultGps?.split(",")[0]);
      _locationAddressController?.text =  gps;
    }
    _locationEditingController?.text = _getAddressStr();
  }

  String _getAddressStr() {
    if (_resultLocationMap == null || _resultLocationMap.isEmpty) {
      // _initLocation();
      if (province == city) {
        return "$province$dirstrict";
      } else {
        return "$province$city$dirstrict";
      }
    }else{
      if(StringUtils.isNotEmpty(_getGpsStr())){
        gps = _getGpsStr();
        _locationAddressController?.text = gps;
      }
      addrCode = _resultLocationMap[CHOOSE_DISTRICT_KEY]?.sid;
      province = _resultLocationMap[CHOOSE_PROVINCE_KEY]?.sname;
      city = _resultLocationMap[CHOOSE_CITY_KEY]?.sname;
      dirstrict = _resultLocationMap[CHOOSE_DISTRICT_KEY]?.sname;
      if(StringUtils.isEmpty(dirstrict)){
        dirstrict = "";
      }
      if (province == city) {
        return "$province$dirstrict";
      } else {
        return "$province$city$dirstrict";
      }
    }
  }

  String _getGpsStr() {
    double   latitude = _resultLocationMap[CHOOSE_DISTRICT_KEY]?.latitude;
    double   longitude = _resultLocationMap[CHOOSE_DISTRICT_KEY]?.longitude;
    return AddressAboutUtils.getLongitudeAndLatitude(longitude?.toString(), latitude?.toString());
  }

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController(text:UserRepository.getInstance().userData.companyInfo.companynick);
    lastPopTime = DateTime.now().add(Duration(minutes: -1));
    _locationEditingController = TextEditingController()
      ..addListener(() => _notifyChange());
    _editingAddressController = TextEditingController()
      ..addListener(() => _notifyChange());
    _locationAddressController = TextEditingController()
      ..addListener(() => _notifyChange());
    _initLocation();
    _viewModel = NewTerminalListViewModel(this, gps: widget?.defaultGps);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFF191E31),
      body: Column(
        children: [
          _toTopBarWidget(),
          _channelOrgHint(),
          _toEditsWidget(),
          SizedBox(height: 30),
          _toBottomWidget(),
        ],
      ),
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "新增地址",
      isShowBack: true,
      isHideRightWidget:true,
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
    );
  }

  Widget _channelOrgHint(){
    return Column(
      children: [
        Container(
          height: 10,
          color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        ),
        Container(
          alignment: Alignment.centerLeft,
          height: 50,
          color: ThemeRepository.getInstance().getCardBgColor_21263C(),
          child: VgTextField(
            controller: _nameController,
            maxLines: 1,
            minLines: 1,
            maxLength: 30,
            autofocus: true,
            decoration: InputDecoration(
              border: InputBorder.none,
              counterText: "",
              contentPadding: const EdgeInsets.only(left: 15,right: 15),
              hintText: "地址名，30字以内",
              hintStyle: TextStyle(
                  color: VgColors.INPUT_BG_COLOR,
                  fontSize: 14),
            ),
            style: TextStyle(
                fontSize: 14,
                color: ThemeRepository.getInstance()
                    .getTextMainColor_D0E0F7()),
            onChanged: (String str) {
              _showBoutton();
            },
          ),
        ),
        Container(
          height: 10,
          color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        ),
      ],
    );
  }

  Widget _toEditsWidget() {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Container(
        // height: 50,
        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
        child: Column(
          children: [
            _EditTextWithTitleWidget(
              controller: _locationEditingController,
              title: "所在区县",
              hintText: "请选择",
              isShowGoIcon: true,
              toJumpCallback: () async {
                HudUtils.showLoading(context,true);
                LocationRepository.getInstance().init(callback: (success)async{
                  HudUtils.showLoading(context,false);
                  Map<String, ChooseCityListItemBean> result =
                  await ChooseCityPage.navigatorPush(context,
                      subLevel: 3, selected: _resultLocationMap);
                  if (result == null || result.isEmpty) {
                    return;
                  }
                  _resultLocationMap = result;
                  _setLocationEditingValue();
                });
              },
            ),
            Container(
              margin: EdgeInsets.only(left: 15),
              height: 1,
              color: Color(0xFF3A3F50),
            ),
            Padding(
              padding: const EdgeInsets.only(left: 15),
              child: _EditTextWithTitleWidget(
                controller: _locationAddressController,
                title: "GPS位置",
                hintText: "请选择",
                isShowGoIcon: true,
                visible:false,
                toJumpCallback: () async {
                  RouterUtils.routeForFutureResult(context, PunchRuleLocationPage(latLng: latLong(),)).then((value){
                    if(value==null) return;
                    Map<String,dynamic> map = value;
                    gps = map["llat"];
                    gpsadress = map["title"];
                    _locationAddressController?.text = gps;
                    setState(() { });
                  });
                },
              ),
            ),
            Container(
              margin: EdgeInsets.only(left: 15),
              height: 1,
              color: Color(0xFF3A3F50),
            ),
            Row(
              children: [
                Container(
                  margin: EdgeInsets.only(left: 4),
                  child: Text(
                    "*",
                    style: TextStyle(
                        color: Color(0xFFFF455E),
                        fontSize: 14
                    ),
                  ),
                ),
                SizedBox(width: 3),
                Container(
                    width: 56,
                    margin: EdgeInsets.only(top: 14, bottom: 15),
                    alignment: Alignment.centerLeft,
                    child: Text("详细地址",
                        style: TextStyle(
                          fontSize: 14,
                          color: ThemeRepository.getInstance()
                              .getTextMinorGreyColor_808388(),
                        ))),
                Expanded(
                  flex: 1,
                  child: Container(
                      margin: EdgeInsets.only(left: 15),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Expanded(
                              flex: 1,
                              child: VgTextField(
                                controller: _editingAddressController,
                                keyboardType: TextInputType.text,
                                style: TextStyle(
                                    color: ThemeRepository.getInstance().getTextColor_D0E0F7(),
                                    fontSize: 14),
                                maxLimitLength: 30,
                                decoration: new InputDecoration(
                                    counterText: "",
                                    hintText: "请输入",
                                    border: InputBorder.none,
                                    hintStyle: TextStyle(
                                        fontSize: 14,
                                        color: VgColors.INPUT_BG_COLOR)),
                              )),
                        ],
                      )),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _toBottomWidget() {
    return InkWell(
      onTap: () async {
        if (intervalClick(2) ?? false) {
          return null;
        }
      },
      child: Container(
        height: 40,
        child: Container(
          margin: EdgeInsets.symmetric(horizontal: 15),
          child: RaisedButton(
            onPressed: () async {
              if(!buttonFull){
                return;
              }
              if(StringUtils.isEmpty(gps)){
                List<String> gpsList = [];
                if(widget?.defaultGps?.contains(",")){
                  gpsList = widget?.defaultGps?.split(",");
                  gps = AddressAboutUtils.getLongitudeAndLatitude(gpsList[1]?.toString(), gpsList[0]?.toString());
                  // gps = "${gpsList[0]?.toString()}°E,${gpsList[1]?.toString()}°N";
                }else{
                  gps = widget?.defaultGps;
                }
              }
              _viewModel.addOrgChannel(context, city, addrCode, dirstrict, province,
                  _editingAddressController?.text?.trim(), _nameController?.text?.trim(),
                  gps, "", gpsadress, (){
                    RouterUtils.pop(context, result: true);
                  });
              setState(() { });
            },
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
            color:buttonFull? ThemeRepository.getInstance().getPrimaryColor_1890FF() : Color(0xFF3A3F50),
            child: Container(
              height: 21,
              alignment: Alignment.center,
              child: Text(
                "保存",
                style: TextStyle(
                    fontSize: 15,
                    color:buttonFull? ThemeRepository.getInstance().getTextMainColor_D0E0F7() : ThemeRepository.getInstance().getHintGreenColor_5E687C()
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  //限制3秒内只能点击一次
  bool intervalClick(int needTime){
    // 防重复提交
    if(lastPopTime == null || DateTime.now().difference(lastPopTime) > Duration(seconds: needTime)){
      lastPopTime = DateTime.now();
      print("允许点击");
      return false;
    }else{
      // lastPopTime = DateTime.now(); //如果不注释这行,则强制用户一定要间隔2s后才能成功点击. 而不是以上一次点击成功的时间开始计算.
      print("请勿重复点击！");
      return true;
    }
  }

  void _showBoutton(){
    if(_locationEditingController?.text!=null && _locationEditingController?.text!=""
        && _editingAddressController?.text!=null && _editingAddressController?.text!=""
        && _nameController?.text!=null && _nameController?.text!=""){
      buttonFull = true;
    }else {
      buttonFull = false;
    }
    setState(() { });
  }
}


/// 带标题的编辑框
///
/// @author: zengxiangxi
/// @createTime: 1/5/21 2:29 PM
/// @specialDemand:
class _EditTextWithTitleWidget extends StatefulWidget {
  final String title;

  final String hintText;

  final bool isShowGoIcon;

  final VoidCallback toJumpCallback;

  final TextEditingController controller;

  final int maxZHCharLimit;

  final bool visible;

  const _EditTextWithTitleWidget(
      {Key key,
        this.title,
        this.hintText,
        this.isShowGoIcon = false,
        this.toJumpCallback,
        this.controller, this.maxZHCharLimit, this.visible})
      : super(key: key);

  @override
  _EditTextWithTitleWidgetState createState() =>
      _EditTextWithTitleWidgetState();
}

class _EditTextWithTitleWidgetState extends State<_EditTextWithTitleWidget> {
  FocusNode _focusNode;

  ValueNotifier<bool> _isShowFocusLineNotifier;

  @override
  void initState() {
    super.initState();
    _isShowFocusLineNotifier = ValueNotifier(false);
    _focusNode = FocusNode();
    _focusNode.addListener(() {
      if (_focusNode?.hasFocus ?? false) {
        _isShowFocusLineNotifier.value = true;
      } else {
        _isShowFocusLineNotifier.value = false;
      }
    });
  }

  @override
  void dispose() {
    _focusNode?.dispose();
    _isShowFocusLineNotifier?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Container(
          height: 45,
          padding: const EdgeInsets.only(right: 15),
          child: Row(
            children: <Widget>[
              Visibility(
                visible: widget?.visible ?? true,
                child: Container(
                  margin: EdgeInsets.only(left: 4,right: 3),
                  child: Text(
                    "*",
                    style: TextStyle(
                        color: Color(0xFFFF455E),
                        fontSize: 14
                    ),
                  ),
                ),
              ),
              Container(
                width: 71,
                alignment: Alignment.centerLeft,
                child: Text(
                  widget.title ?? "",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: ThemeRepository.getInstance()
                        .getTextMinorGreyColor_808388(),
                    fontSize: 14,
                  ),
                ),
              ),
              Expanded(
                child: VgTextField(
                  controller: widget?.controller,
                  maxLines: 1,
                  focusNode: _focusNode,
                  readOnly: widget.toJumpCallback != null ? true : false,
                  onTap: () {
                    if (widget.toJumpCallback != null) {
                      widget.toJumpCallback();
                    }
                  },
                  maxLimitLength: widget?.maxZHCharLimit,
                  decoration: InputDecoration(
                    border: InputBorder.none,
                    counterText: "",
                    contentPadding: const EdgeInsets.only(bottom: 2),
                    hintText: widget.hintText ?? "",
                    hintStyle: TextStyle(
                        color: VgColors.INPUT_BG_COLOR,
                        fontSize: 14),
                  ),
                  style: TextStyle(
                      fontSize: 14,
                      color: ThemeRepository.getInstance()
                          .getTextMainColor_D0E0F7()),
                ),
              ),
              Opacity(
                opacity: widget.isShowGoIcon ? 1 : 0,
                child: Container(
                    padding: const EdgeInsets.only(left: 5),
                    child: Image.asset(
                      "images/index_arrow_ico.png",
                      width: 6,
                    )),
              )
            ],
          ),
        ),
      ],
    );
  }
}
